package com.intelligentpension.kotlinwifi

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.hjq.toast.ToastUtils
import com.intelligentpension.utils.ThreadUtils
import java.io.*
import java.net.InetSocketAddress
import java.net.Socket


class SendAndReceivedActivity : AppCompatActivity() {

    private var ip: String = "192.168.4.1" //设置IP地址
    private var port: Int = 8080//设置端口号
    private lateinit var mSocket: Socket
    private lateinit var mReceived: TextView
    private lateinit var mSend: Button
    private lateinit var mMessage: EditText
    private var OUTCONNECTTIME: Int = 3500
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_send_and_received)
        mReceived = findViewById<TextView>(R.id.recevied)
        mMessage = findViewById<EditText>(R.id.message_send)
        mSend = findViewById<Button>(R.id.send)


        ThreadUtils.executeSubThread {
            mSocket = Socket()
            mSocket.connect(InetSocketAddress(ip, port), OUTCONNECTTIME)
            mSocket.keepAlive = true
            if (mSocket.isConnected) {
                ThreadUtils.executeMainThread {
                    ToastUtils.show("连接了socket")
                }
            }

            var inputStream = mSocket.getInputStream()

            var reader = InputStreamReader(inputStream)

            while (true) {
                var len: Int = 0
                var chars: CharArray = CharArray(4096)
                var str: String = ""
                while (reader.read(chars).also { len = it } != -1) {
                    var reader = String(chars, 0, len)
                    str += reader
                    //接受数据
                    ThreadUtils.executeMainThread {
                        mReceived.append(str + "\n")
                        str = ""
                    }
                }
            }
        }

        mSend.setOnClickListener {

            var received = mMessage.text.toString()

            Thread(Runnable {
                if (mSocket.isConnected) {
                    ThreadUtils.executeMainThread {
                        ToastUtils.show("发送了" + received + "信息")
                    }
                    var outputStream = mSocket.getOutputStream()
                    outputStream.write(received.toByteArray(charset("GBK")));
                    outputStream.flush();
                }else{
                    ThreadUtils.executeMainThread {
                        ToastUtils.show("别点了,连接断开了")
                    }
                }
            }).start()

        }
    }

    //解码
    private fun getInfoBuff(paramArrayOfChar: CharArray, paramInt: Int): String {
        synchronized(this) {
            val arrayOfChar = CharArray(paramInt)
            var b = 0
            try {
                b = 0
                while (true) {
                    if (b >= paramInt) {
                        return String(arrayOfChar)
                    }
                    arrayOfChar[b] = paramArrayOfChar[b]
                    b++
                }
            } catch (e: Exception) {
                e.printStackTrace()
                return String(arrayOfChar)
            }
        }
    }

    //byte数组转String
    fun bytesToHexString(bArray: ByteArray): String {
        val sb = StringBuffer(bArray.size)
        var sTemp: String
        for (i in bArray.indices) {
            sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
            if (sTemp.length < 2) sb.append(0)
            sb.append(sTemp.toUpperCase())
        }
        var length = sb.length
        if (length == 1 || length == 0) {
            return sb.toString()
        }
        if (length % 2 == 1) {
            sb.insert(length - 1, " ")
            length = length - 1
        }
        var i = length
        while (i > 0) {
            sb.insert(i, " ")
            i = i - 2
        }
        return sb.toString()
    }
}